<?php

namespace App\Http\Controllers;

use App\Model\Article;
use App\Model\User;
use Illuminate\Http\Request;
use Mews\Captcha\Facades\Captcha;

class UserController extends Controller
{
    private $pagesize = 0;
    public function __construct()
    {
        $this->pagesize = env('PAGESIZE');
        // 控制器绑定中间件
        // $this->middleware('ck:aa');
    }

    //列表
    public function index(Request $request){
        // 关联一对一1
        // $user = User::find(1);
        // dump($user->userExt);
        // 关联一对一2
        // $user = User::with('userExt')->find(1);
        // dump($user->userExt->addr);
        // 关联一对多1
        // $user = User::find(1);
        // dump($user->arts()->get()->toArray());
        // $user = User::with('arts')->find(1);
        // $user = User::with(['arts'=>function($request){
        //     $request->where('id','>=',2);
        // },'userExt'])->find(1);
        // dump($user);
        // 多对多
        // $user = User::with('auths')->find(1);
        // dump($user->auths->pluck('name','id'));
        // dump($user->auths->toArray());
        // 添加权限
        // $user = User::find(1);
        // $user->auths()->sync([1,5]);
        // 属于关系
        // dump(Article::with('username')->find(1));
        // 列表渲染
        $data = User::paginate($this->pagesize);
        return view('index',compact('data'));
    }

    // 软删除
    public function del(int $id){
        User::destroy($id);
        return ['status' => 0,'msg' => '删除成功'];
    }

    
    // 全部删除
    public function deleteAll(Request $request){
        $ids = $request->get('ids');
        User::destroy($ids);
        return ['status' => 0,'msg' => '删除成功'];
    }

    // 添加显示
    public function add(){
        return view('add');
    }
    // 添加处理
    public function save(Request $request){
        $this->validate($request,[
            'username' => 'required|unique:users,username',
            'password' => 'required'
        ]);
        $input = $request->except(['_token','file']);
        // 默认头像
        $input['pic'] = 'http://b-ssl.duitang.com/uploads/item/201509/30/20150930140213_ZCFSr.jpeg';
        // 判断是否有上传头像
        if ($request->hasFile('file')) {
            // 得到上传的file对象
            $file = $request->file('file');
            // 扩展名
            $ext = $file->getClientOriginalExtension();
            // 文件名
            $filename = time().'.'.$ext;
            // 上传
            $file->move(public_path('uploads'),$filename);
            $input['pic'] = '/uploads/'.$filename;
        }
        User::create($input);
        // 设置闪存
        return redirect(route('index'))->with('msg','新增成功');
    }
}
